package cc.chengheng.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 退出
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

        //配置url的访问权限
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/**update**").permitAll()
                .antMatchers("/login/**").permitAll()
                .anyRequest().authenticated();


//        http.csrf().disable(); // 关闭csrf防护

        //使用自定义的登录窗口
        http.formLogin()
                .loginPage("/userLogin").permitAll()
                .usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/userLogin?error");



        /*http.formLogin() // 自定义自己编写的登陆页面
            .loginPage("/userLogin").permitAll() // 登陆页面设置
            .loginProcessingUrl("/user/login") // post 表单或者ajax请求的url自定义设置,这个不需要配置Controller
            .defaultSuccessUrl("/success.html") // 登陆成功，跳转的路径, 这个需要配置Controller
            .permitAll()
            .and()
            .authorizeRequests() // 哪些可以访问， 哪些需要授权
            .antMatchers("/", "/test/hello","/user/login").permitAll() // 这些路径，不需要认证可以直接访问

            // 当前登陆的用户，只有具有admin权限才可以访问这个路径
            //.antMatchers("/test/index").hasAuthority("admin")

            // 当前登陆的用户，多个权限只要有任意一个权限就可以访问这个路径
            //.antMatchers("/test/index").hasAnyAuthority("admin,manager")

            // ROLE_sale
            .antMatchers("/test/index").hasRole("sale")
            .anyRequest().authenticated();*/
    }
}
